package com.cn.book.intercepter;

import com.alibaba.fastjson.JSON;
import com.cn.book.util.UserPermissionUtil;
import com.cn.book.vo.User;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

public class UserContextInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = getUser(request);
        UserPermissionUtil.permission(user);
        if (!UserPermissionUtil.verify(user, request)) {
            response.setHeader("Content-Type", "application/json");
            String jsonstr = JSON.toJSONString("no permisson access service, please check");
            response.getWriter().write(jsonstr);
            response.getWriter().flush();
            response.getWriter().close();
            throw new PermissionException("no permisson access service, please check");
        }

        UserContextHolder.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //do nothing
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.shutdown();
    }

    private User getUser(HttpServletRequest request) {
        String id = request.getHeader("x-user-id");
        String name = request.getHeader("x-user-name");
        User user = new User();
        user.setUserId(id);
        user.setUserName(name);
        return user;
    }

    static class PermissionException extends RuntimeException implements Serializable {

        private static final long serialVersionUID = 5826238887641221308L;

        public PermissionException(String message) {
            super(message);
        }
    }
}
